<?php

namespace App\Repository\Db;

use App\Repository\Contracts\EvaluateInterface;
use App\Repository\Contracts\EvaluateResultInterface;

/**
 * @Author:: Linch
 * @DateTime: 2017/11/12
 */
class EvaluateRepository extends Repository implements EvaluateInterface
{
    protected $rules = [
        'created' => [
            'uid' => 'required|integer',
            'type' => 'required',
            'result' => 'required',
        ]
    ];

    protected $messages = [
        'uid.required'         => "用户 ID 不能为空",
        'uid.integer'          => "用户 ID 必须是整数",
        'type.required'        => "评测类型不能为空",
        'result.required'      => "评测结果不能为空",
    ];

    protected function modelName()
    {
        return 'App\Model\Evaluate';
    }

    public function lists($uid)
    {
        $query = $this->model->where('uid', '=', $uid);
        $total = $query->count();
        $columns = ['type', 'result', 'key'];
        $data = $query->orderBy('id', 'desc')->get($columns);

        return $this->simplePaginate('list', $data, $total);
    }

    public function created(array $data)
    {
        $this->validate($data, 'created');
//        $result = $this->container->make(EvaluateResultInterface::class)->findByKey($data['key']);
        $model = $this->model->where('uid', '=', $data['uid'])
            ->where('type', '=', $data['type'])->first();
        if (!$model) {
            $this->save($data);
            return $this->model;
        }
        $model->update($data);
        return $model;
    }

    public function detail($id)
    {
        return $this->find($id);
    }
}